//
//  AppDelegate.m
//  Inner  Voice
//
//  Created by 徐海宇 on 16/2/27.
//  Copyright © 2016年 徐海宇. All rights reserved.
//

#import "AppDelegate.h"

#import "InMainTabBarViewController.h"

#import "InPlayerViewController.h"

#define player  [InPlayer sharedInstance]

#import "InPlayer.h"

#import "InNewFeatureControllerViewController.h"

#import "RecommenViewController.h"

#import "InChannelViewController.h"

@interface AppDelegate ()

@property (nonatomic, strong) UITabBarController *taBarContro;

@end

@implementation AppDelegate
#pragma mark - 新特性
- (void)testNewFeature {
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

    NSString *key = @"versionID";
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    NSString *lastVersisonStr = [userDefault objectForKey:key];
    NSString *currentVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];

//    新旧版本
//    NSLog(@"123%@",lastVersisonStr);
//    NSLog(@"345%@",currentVersion);
    if ([lastVersisonStr isEqualToString:currentVersion]) {
        
        self.window.rootViewController = [[InMainTabBarViewController alloc]init];
        
    }else {
        
        self.window.rootViewController = [[InNewFeatureControllerViewController alloc] init];
        [userDefault setObject:currentVersion forKey:key];
        [userDefault synchronize];
    }
    
    self.InPlayerViewController = [[InPlayerViewController alloc]initWithNibName:@"InPlayerViewController" bundle:nil];
    
    self.InPlayerViewController.view.backgroundColor = [UIColor whiteColor];
    
    self.InPlayerViewController.inplayer = player;
    //如果这一句删掉的话 点击歌曲不会播放 一定要先进到播放器界面后  再点歌曲 歌曲才能播放 而且 滑块还在 在InPlayer.m的第187 行有改动(取消遮罩 不然会崩)  现在的问题是 加上这一句 点击歌曲能播放 但是进到播放界面后  滑块消失 再怎么点都不出来
    //在单例的view上播放
    
    //    UIView *playingView = [[UIView alloc]initWithFrame:CGRectMake(0,500, self.window.frame.size.width, 100)];
    //    self.playingView = playingView;
    //    self.playingView.backgroundColor = [UIColor redColor];
    //    self.playingView.hidden = NO;
    //    [self.viewController.view addSubview:self.playingView];
    //  NSLog(@"%@",self.playingView);
    
    NSLog(@"%@",player.playSlider);
    [self loadSaveData];
    [self.window makeKeyAndVisible];

}

+ (AppDelegate *)shareAppdelegate{
    return [[UIApplication sharedApplication]delegate];
}


- (BOOL)canConnectedToTheInternet {
    if (self.network == 2 || self.network == 3) {
        return YES;
    } else {
        return NO;
    }
}
//监控网络状态
- (void)setNetworkManager {
    AFNetworkReachabilityManager *networkMaanger = [AFNetworkReachabilityManager sharedManager];
    
    [networkMaanger setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status) {
            case AFNetworkReachabilityStatusNotReachable:
                NSLog(@"无网络");
                [self showAlertView:@"当前网络不可用"];
                self.network = 0;
                break;
            case AFNetworkReachabilityStatusReachableViaWiFi:
                NSLog(@"wifi");
                self.network = 2;
                break;
            case AFNetworkReachabilityStatusReachableViaWWAN:
                NSLog(@"移动网络");
                self.network = 3;
                break;
            case AFNetworkReachabilityStatusUnknown:
                NSLog(@"未知网络");
                [self showAlertView:@"当前网络不可用"];
                self.network = 1;
                break;
        }
    }];
    [networkMaanger startMonitoring];
}

//- (void)setKeyboardManager {
//    //启用键盘管理工具
//    IQKeyboardManager *manager = [IQKeyboardManager sharedManager];
//    manager.enable = YES;
//    //显示工具条
//    manager.enableAutoToolbar = YES;
//    //设置点击屏幕收起键盘
//    manager.shouldResignOnTouchOutside = YES;
//    //设置键盘完成键的title
//    manager.toolbarDoneBarButtonItemText = @"完成";
//    
//    manager.shouldToolbarUsesTextFieldTintColor = YES;
//}
- (void)showAlertView:(NSString *)string {
    UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:string delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
    [alertView show];
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    [self setNetworkManager];
    
    [self testNewFeature];
        
    return YES;

}


//沙盒
+ (NSString *)sandBoxPath {
    NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
    NSString *path = [doc stringByAppendingPathComponent:@"InSound.data"];
    return path;
}


- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    
    
//    BOOL Success = [NSKeyedArchiver archiveRootObject:self.InPlayerViewController.playingSoundArray
//                                               toFile:[AppDelegate sandBoxPath]];
//    if (Success) {
//        NSLog(@"AppDelegate保存成功");
//    } else {
//        NSLog(@"AppDelegate保存失败");
//    }
}



- (void)removeBox {
    [[NSFileManager defaultManager] removeItemAtPath:[AppDelegate sandBoxPath] error:nil];
}

- (void)loadSaveData {
    
    if ([[NSFileManager defaultManager] fileExistsAtPath:[AppDelegate sandBoxPath]]) {
        NSLog(@"AppDelegate读取沙盒");
        //可以做成一个属性
        self.InPlayerViewController.playingSoundArray = [NSKeyedUnarchiver unarchiveObjectWithFile:[AppDelegate sandBoxPath]];
    }
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    // Saves changes in the application's managed object context before the application terminates.
    [self saveContext];
}

#pragma mark - Core Data stack

@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;

- (NSURL *)applicationDocumentsDirectory {
    // The directory the application uses to store the Core Data store file. This code uses a directory named "xhy.Inner__Voice" in the application's documents directory.
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

- (NSManagedObjectModel *)managedObjectModel {
    // The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.
    if (_managedObjectModel != nil) {
        return _managedObjectModel;
    }
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"Inner__Voice" withExtension:@"momd"];
    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return _managedObjectModel;
}

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
    // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it.
    if (_persistentStoreCoordinator != nil) {
        return _persistentStoreCoordinator;
    }
    
    // Create the coordinator and store
    
    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"Inner__Voice.sqlite"];
    NSError *error = nil;
    NSString *failureReason = @"There was an error creating or loading the application's saved data.";
    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
        // Report any error we got.
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        dict[NSLocalizedDescriptionKey] = @"Failed to initialize the application's saved data";
        dict[NSLocalizedFailureReasonErrorKey] = failureReason;
        dict[NSUnderlyingErrorKey] = error;
        error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict];
        // Replace this with code to handle the error appropriately.
        // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
        NSLog(@"AppDelegate Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }
    
    return _persistentStoreCoordinator;
}


- (NSManagedObjectContext *)managedObjectContext {
    // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.)
    if (_managedObjectContext != nil) {
        return _managedObjectContext;
    }
    
    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (!coordinator) {
        return nil;
    }
    _managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
    [_managedObjectContext setPersistentStoreCoordinator:coordinator];
    return _managedObjectContext;
}

#pragma mark - Core Data Saving support

- (void)saveContext {
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if (managedObjectContext != nil) {
        NSError *error = nil;
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
            // Replace this implementation with code to handle the error appropriately.
            // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            NSLog(@"AppDelegate Unresolved error %@, %@", error, [error userInfo]);
            abort();
        }
    }
}

@end
